package com.itheima.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author xiaycbstart
 * @create 2019 12 29 20:00
 */
public class SpringSecurityUserService implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    public  static  Map<String, com.itheima.pojo.User> map = new HashMap<>();

    public void initData() {
        com.itheima.pojo.User user1 = new com.itheima.pojo.User();
        user1.setUsername("admin");
        user1.setPassword(passwordEncoder.encode("admin"));
        com.itheima.pojo.User user2 = new com.itheima.pojo.User();
        user2.setUsername("xiaoming");
        user2.setPassword(passwordEncoder.encode("1234"));
        map.put(user1.getUsername(), user1);
        map.put(user2.getUsername(), user2);
    }
    //username来源于页面输入
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initData();
        com.itheima.pojo.User userInDb = map.get(username);
        if (userInDb == null) {
        //根据用户名没有查询到用户
            return null;
        }
        String passwordInDb = userInDb.getPassword();
        List<GrantedAuthority> list = new ArrayList<>();

        //授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
        list.add(new SimpleGrantedAuthority("permission_A"));
        list.add(new SimpleGrantedAuthority("permission_B"));
        String u = "admin";
        if (u.equals(username)) {
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            list.add(new SimpleGrantedAuthority("add"));
        }
        UserDetails user = new User(username, passwordInDb, list);
        return user;
    }
}
